<template>
  <!-- 编辑广告活动 -->
  <a-modal :width="1000" v-model:visible="showEditDialog" title="编辑广告活动" title-align="start" :mask-closable="false" @cancel="closedDialog" :ok-loading="submitLoading" :on-before-ok="saveData">
    <a-form ref="formRef" :model="editSpCampaignInfo" :rules="rules">
      <div class="base">
        <div class="edit-header">
          <p>广告活动</p>
        </div>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="店铺" label-col-flex="100px">
              <p>{{ editSpCampaignInfo.shopName }}</p>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="销售员" label-col-flex="100px">
              <p>{{ editSpCampaignInfo.ownerName }}</p>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="campaignName" label="活动名称" label-col-flex="100px">
              <a-input v-model="editSpCampaignInfo.campaignName" placeholder="请输入" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="活动ID" label-col-flex="100px">
              <p>{{ editSpCampaignInfo.campaignId }}</p>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="广告组合" label-col-flex="100px">
              <p>{{ editSpCampaignInfo.portfolioName }}</p>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="广告活动时间" label-col-flex="100px">
              <a-date-picker disabled style="margin-right: 5px" v-model="editSpCampaignInfo.startDate" placeholder="开始日期(必填)" />
              <a-date-picker disabled v-model="editSpCampaignInfo.endDate" placeholder="结束日期" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="budgetAmount" label="每日预算" label-col-flex="100px">
              <a-input-number v-model="editSpCampaignInfo.budgetAmount" placeholder="" allow-clear>
                <template #prepend>
                  <a-button>{{ $extract(marketPlaceList[shop.marketplaceId], 'currency') || 'USD' }}</a-button>
                </template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="targeting" label="投放类型" label-col-flex="100px">
              <a-radio-group disabled v-model="editSpCampaignInfo.targetingType">
                <a-radio value="AUTO">
                  <span>自动投放</span>
                  <a-popover content="马逊将定向到关键词和与您广告中的商品类似的商品。">
                    <icon-question-circle style="margin-left: 2px" />
                  </a-popover>
                </a-radio>
                <a-radio value="MANUAL">
                  <span>手动投放</span>
                  <a-popover content="择可定向到顾客搜索的关键词或商品并设置自定义竞价。">
                    <icon-question-circle style="margin-left: 2px" />
                  </a-popover>
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <div class="bid-w">
        <div class="edit-header">
          <p>广告活动竞价策略</p>
        </div>
        <a-radio-group v-model="editSpCampaignInfo.dynamicBudgetStrategy" direction="vertical">
          <a-radio value="LEGACY_FOR_SALES">
            <p>动态竞价 - 仅降低</p>
            <p class="info">当您的广告不太可能带来销售时，我们将实时降低您的竞价。</p>
          </a-radio>
          <a-radio value="AUTO_FOR_SALES">
            <p>动态竞价 - 提高和降低</p>
            <p class="info">当您的广告很有可能带来销售时，我们将实时提高您的竞价（最高可达 100%），并在您的广告不太可能带来销售时降低您的竞价。</p>
          </a-radio>
          <a-radio value="MANUAL">
            <p>固定竞价</p>
            <p class="info">我们将使用您的确切竞价和您设置的任何手动调整，而不会根据售出可能性对您的竞价进行更改。</p>
          </a-radio>
        </a-radio-group>
        <div class="change-price-w flex">
          <div class="icon-w" @click="expaned = !expaned">
            <icon-right v-show="!expaned" />
            <icon-down v-show="expaned" />
          </div>
          <div>
            <p>根据广告位调整竞价（取代“竞价+”）</p>
            <p class="info" style="margin-bottom: 20px">除了竞价策略外，您可以将竞价最多提高 900%</p>
            <template v-if="expaned">
              <div class="flex-c" style="margin-bottom: 10px">
                <span class="label">搜索结果顶部(首页)：</span>
                <a-input-number style="width: 100px" size="mini" v-model="editSpCampaignInfo.adjustmentAdsPlacementTopSearchPercentage" @blur="changePrice('adjustmentAdsPlacementTopSearchPercentage', 'price1')" placeholder="" :max="900" />
                <span style="margin-right: 20px">%</span>
                <p class="info">
                  <span>示例：对于此广告位，</span>
                  <span v-if="!demoPrices.price1">$1竞价将保持 $1 不变。</span>
                  <span v-else>$1竞价将为 ${{ demoPrices.price1 }}。</span>
                </p>
              </div>
              <div class="flex-c">
                <span class="label">商品页面：</span>
                <a-input-number style="width: 100px" size="mini" v-model="editSpCampaignInfo.adjustmentAdsPlacementProductDetailPercentage" @blur="changePrice('adjustmentAdsPlacementProductDetailPercentage', 'price2')" placeholder="" :max="900" />
                <span style="margin-right: 20px">%</span>
                <p class="info">
                  <span>示例：对于此广告位，</span>
                  <span v-if="!demoPrices.price2">$1竞价将保持 $1 不变。</span>
                  <span v-else>$1竞价将为 ${{ demoPrices.price2 }}。</span>
                </p>
              </div>
            </template>
          </div>
        </div>
      </div>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getCampaignDetail, editCampaign } from '@/api/advert'
  import { marketPlaceList } from '@/utils/globalData'
  import { parseJson } from '@/utils'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
    shop: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(() => {
    getCampaignInfo()
  })
  const rules = ref({
    campaignName: [{ required: true, message: '请输入活动名称' }],
    budgetAmount: [{ required: true, message: '请输入每日预算' }],
  })

  const showEditDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const editSpCampaignInfo = ref<any>({})
  const expaned = ref(false)
  const demoPrices = ref<any>({})
  const formRef = ref()

  // 获取广告活动详情
  async function getCampaignInfo() {
    const res: any = await getCampaignDetail({
      campaignId: props.currentItem?.campaignId,
      shopId: props.shop?.shopId,
    })
    editSpCampaignInfo.value = res?.data || {}
    // 竞价策略
    if (editSpCampaignInfo.value.dynamicBudgetPlacementBidding) {
      let dynamicBudgetPlacementBidding = parseJson(editSpCampaignInfo.value.dynamicBudgetPlacementBidding, [])
      dynamicBudgetPlacementBidding.forEach((el: any) => {
        if (el.placement == 'PLACEMENT_TOP') {
          editSpCampaignInfo.value.adjustmentAdsPlacementTopSearchPercentage = el.percentage
        }
        if (el.placement == 'PLACEMENT_PRODUCT_PAGE') {
          editSpCampaignInfo.value.adjustmentAdsPlacementProductDetailPercentage = el.percentage
        }
      })
      expaned.value = true
    }
  }

  // 编辑调整竞价
  function changePrice(valKey: string, key: string) {
    let val = editSpCampaignInfo.value[valKey]
    demoPrices.value[key] = val ? ((1 + val / 100) * 1).toFixed(2) : undefined
  }
  // 同步
  async function saveData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let params = {
      adType: editSpCampaignInfo.value.adType,
      shopId: editSpCampaignInfo.value.shopId,
      campaignName: editSpCampaignInfo.value.campaignName,
      campaignId: editSpCampaignInfo.value.campaignId,
      budgetAmount: editSpCampaignInfo.value.budgetAmount,
      bidStrategy: editSpCampaignInfo.value.dynamicBudgetStrategy,
      adjustmentAdsPlacementProductDetailPercentage: editSpCampaignInfo.value.adjustmentAdsPlacementProductDetailPercentage,
      adjustmentAdsPlacementTopSearchPercentage: editSpCampaignInfo.value.adjustmentAdsPlacementTopSearchPercentage,
    }
    const res: any = await editCampaign(params)
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    emit('closed')
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 20px;
  }
  :deep(.arco-input-prepend) {
    padding: 0;
  }
  .bid-w {
    .arco-radio {
      line-height: 18px;
      margin-bottom: 20px;
    }
    .info {
      font-size: 12px;
      color: #999;
      margin-top: 2px;
    }
    .change-price-w {
      padding-left: 5px;
      .icon-w {
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
      .label {
        width: 140px;
        text-align: right;
      }
    }
  }
</style>
